#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "transfer.h"
#include "html_utils.h"
#include "setup.h"
#include "strings.h"

#define BLOCK_SIZE 100
#define MAX_FILE_NAME_LENGTH 500


CLIENT * client_create(char * host)
{
  CLIENT * result = clnt_create(host, PAPER_PROG, FIRST_VERS, "tcp");
  if (result == 0) {
    http_error("Internal error: Unanable to connect to paperserver.\n");
  }
  return result;
}

void create_block_request(block_request_t * request, int paper_id, int block_id)
{
  request->paper_id = paper_id;
  request->block_id = block_id;
}


void fetch(char * host_name, int paper_id)
{
  CLIENT * client = client_create(host_name);
  struct paper_info_t * paper_info;
  paper_info = get_paper_1(&paper_id, client);

  if (paper_info->error) {
    http_error(paper_info->error_message);
  }

  FILE * file = stdout;

  block_request_t request;
  block_t * block;
  int i = 0;

  char type[20];
  get_mime_type_by_filename(paper_info->file_name, type);
  header(type);

  do {
    create_block_request(&request, paper_id, i++);
    block = get_block_1(&request, client);

    if (block->error) {
      http_error("Internal error: unanable too find document by id\n");
      return;
    }

    if (block->size > 0) {
      if (fwrite(block->data,1, block->size,file) < 0) {
        http_error("Error in writing\n");
	return;
     }
    }

  } while (block->size > 0);

  fclose(file);
  clnt_destroy(client);
}



int get_paper_id(char * * argv)
{
  char id_variable_string[100];
  char id_string[100];
  int i = 0;
  for (i = 0; argv[i] != 0; i++) {
    int r = sscanf(argv[i], "QUERY_STRING=%s", id_variable_string);
    if (r > 0) {
      r = sscanf(id_variable_string, "id=%s", id_string);
      if (r > 0) {
       return atoi(id_string);
      }
    }
  }
  return -1;
}


int main(int argi, char * * args, char * * argv)
{
  int id = get_paper_id(argv);
  if (id < 0)
    http_error("Wrong arguments");     

  fetch(PAPER_SERVER_HOST, id);
  return 0;
}
